package com.jiangore.extension.log;


import com.alibaba.druid.pool.DruidDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/**
 * ConnectionFactory 是一个实现 Druid 连接池的单例类
 *
 * @Author jiangtao
 * @CreateBy 2019-07-18 10:52 AM
 * @UpdateBy jiangtao
 * @Version v1.0
 */
public class MySQLConnectionFactory {

    private final DataSource dataSource;

    public MySQLConnectionFactory() {
        Properties properties = new Properties();
        properties.setProperty("druid.username", "root");
        properties.setProperty("druid.password", "123456");
        properties.setProperty("druid.dbType", "mysql");
        properties.setProperty("druid.driverClassName", "com.mysql.cj.jdbc.Driver");
        properties.setProperty("druid.url", "jdbc:mysql://127.0.0.1:3306/db_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai");
        /*try {
            InputStream stream =  MySQLConnectionFactory.class.getClassLoader().getResourceAsStream("db/mysql.properties");
            properties.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        this.dataSource = new DruidDataSource();
        ((DruidDataSource) this.dataSource).configFromPropety(properties);
    }

    private static interface Singleton {
        final MySQLConnectionFactory INSTANCE = new MySQLConnectionFactory();
    }

    public static Connection getDatabaseConnection() throws SQLException {
        return Singleton.INSTANCE.dataSource.getConnection();
    }
}
